<template>
  <div class='container'>
    <el-card class="box-card">
      <!-- 头部 -->
      <div slot="header" class="clearfix">
        <span>{{$route.query.id ? '编辑试题':'试题录入'}}</span>
      </div>

      <!-- 内容 -->
      <el-form :model="formDate" ref="formDate" :rules="rules">
        <!-- 学科 -->
        <el-form-item label="学科: " prop="subjectID">
          <el-select
            placeholder="请选择学科"
            clearable
            v-model="formDate.subjectID"
            @change='getDirectoryAndTag'
            style="width: 444px;" >
            <el-option
              v-for="(obj,index) in formDateArr.subjectID"
              :key="index" :value="obj.value"
              :label="obj.label"
            >
            </el-option>

          </el-select>
        </el-form-item>
        <!-- 目录 catalogID-->
        <el-form-item label="目录: " prop="catalogID">
          <el-select
            placeholder="请选择目录"
            style="width: 444px;"
            clearable
            v-model="formDate.catalogID"
          >
            <el-option
              v-for="(obj,index) in formDateArr.catalogID"
              :key="index"
              :value="obj.value"
              :label="obj.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 企业： -->
        <el-form-item label="企业: " prop='enterpriseID'>
          <el-select
            placeholder="请选择企业"
            style="width: 444px;"
            clearable
            v-model="formDate.enterpriseID"
          >
            <el-option
              v-for="(obj,index) in formDateArr.enterpriseID"
              :key="index" :value="obj.value"
              :label="obj.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 城市： -->
        <el-form-item label="城市: " prop="province" class="city">
          <!-- 城市 -->
          <el-select
            class="cselect"
            placeholder="请选择城市"
            clearable
            v-model="formDate.province"
            @change="getcitys"
          >
            <el-option
              v-for="(obj,index) in formDateArr.province"
              :key="index" :value="obj.value"
              :label="obj.label"
            >
            </el-option>
          </el-select>

        </el-form-item>
        <!-- 地区 -->
        <el-form-item class="city mycity" prop="city">
          <el-select
            class="cselect cityfd"
            placeholder="请选择地区"
            clearable
            v-model="formDate.city"
          >
            <el-option
              v-for="(obj,index) in formDateArr.city"
              :key="index" :value="obj.value"
              :label="obj.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
         <!-- 方向： -->
        <el-form-item label="方向: " prop="direction">
           <el-select
            class="cselect"
            style="width: 444px;"
            placeholder="请选择方向"
            clearable
            v-model="formDate.direction"
          >
            <el-option
               v-for="(obj,index) in formDateArr.direction"
              :key="index"
              :value="obj.value"
              :label="obj.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型: " prop="questionType">
           <el-radio-group
              v-model="formDate.questionType"
              @change="changedx"
            >
            <el-radio
             v-for="(obj,index) in formDateArr.questionType"
            :key="index"
            :label="obj.value"
            >{{obj.label}}</el-radio>

          </el-radio-group>
        </el-form-item>
        <!-- 难度 difficulty-->
        <el-form-item label="难度: " prop="difficulty">
           <el-radio-group v-model="formDate.difficulty">
            <el-radio
              v-for="(obj,index) in formDateArr.difficulty"
              :key="index"
              :label="obj.value"
            >{{obj.label}}</el-radio>

          </el-radio-group>
        </el-form-item>

        <!-- 题干 -->
        <el-form-item label="题干: " prop="question">
          <div id="question1"></div>
        </el-form-item>

        <!-- 选项 -->
        <el-form-item label="选项: "  v-if='formDate.questionType !== 3'>
          <!-- 单选 -->
          <el-radio-group v-if='formDate.questionType === 1' v-model="dx">
            <div v-for="(obj,index) in formDate.options" :key='index'>
              <el-radio
                :label="index"
                class="myradio"

              >
                {{obj.code}} : <el-input v-model="obj.title" placeholder="请输入内容" />
              </el-radio>
            </div>

          </el-radio-group>
          <br>
          <!-- 多选 -->
          <el-checkbox-group v-model="checkList" v-if='formDate.questionType === 2'>
            <div v-for="(obj,index) in formDate.options" :key='index'>
              <el-checkbox
                :label="index"
                class="myradio"

              >
                {{obj.code}} : <el-input v-model="obj.title" placeholder="请输入内容" />
              </el-checkbox>
            </div>
          </el-checkbox-group>
          <el-button
            class="myradio ml"
            type="danger"
            :disabled='formDate.questionType === 2 ? false: true'
            @click="addcheck"
          >+ 增加选项与答案</el-button>
        </el-form-item>

         <!-- 解析视频 -->
        <el-form-item label="解析视频: ">
          <el-input v-model="formDate.videoURL"  style="width: 410px;"></el-input>

        </el-form-item>

        <!-- 答案解析 -->
        <el-form-item label="答案解析: " prop="answer" class="myquestion2">
          <div id="question2"></div>
        </el-form-item>

        <!-- 题目备注 -->
        <el-form-item label="题目备注: ">
            <el-input
              style="width: 410px;"
              type="textarea"
              :autosize="{ minRows: 5, maxRows: 5}"
              placeholder="请输入内容"
              v-model="formDate.remarks"
              >
            </el-input>
        </el-form-item>

        <!-- 试题标签 -->
        <el-form-item label="试题标签: " prop="tags">
          <el-select
            style="width: 410px;"
            v-model="formDateArr.tag"
            multiple
            filterable
            default-first-option
            @change="changeTags"
            placeholder="请选择试题标签">
            <el-option
              v-for="(obj,index) in formDateArr.tags"
              :key="index" :value="obj.label"
              :label="obj.label"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="submmit" @click="submmit" :disabled='disabled'>{{$route.query.id ? '编辑试题':'试题录入'}}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

  </div>
</template>

<script>
import WangEditor from 'wangeditor' // 富文本
import { simple as simplesubjects } from '@/api/hmmm/subjects.js' // 学科列表
import { simple as simpledirectorys } from '@/api/hmmm/directorys.js' // 目录列表
import { simple as listTags } from '@/api/hmmm/tags.js' // 标签列表
import { list as listcompanys } from '@/api/hmmm/companys.js' // 企业列表详情
import { provinces, citys } from '@/api/hmmm/citys.js' // provinces城市 citys 地区
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js' // direction方向  questionType题型 difficulty难度
import { add as addQuestions, detail as detailecho, update as updateQuestions } from '@/api/hmmm/questions.js'
export default {
  name: 'stlr',
  data () {
    // 答案校验
    var answerrules = (rule, value, callback) => {
      if (value) {
        callback()
      } else {
        document.querySelector('#question2').classList.add('question1')
        callback(new Error('答案解析不能为空'))
      }
    }
    // 题干校验
    var questionrules = (rule, value, callback) => {
      if (value) {
        callback()
      } else {
        document.querySelector('#question1').classList.add('question1')
        callback(new Error('答案解析不能为空'))
      }
    }
    return {
      editor: null, // 富文本
      editor2: null,
      dx: '', // 单选
      checkList: [], // 复选
      disabled: false, // 按钮
      formDateArr: {
        subjectID: [], // 学科
        catalogID: [], // 目录
        enterpriseID: [], // 企业
        province: [], // 城市
        city: [], // 地区
        direction: [], // 方向
        questionType: [], // 题型
        difficulty: [], // 难度
        tags: [], // 所有标签
        tag: [], // 标签选中数据
        mysort: 68, // 排序
        initValue: 4 // 排序id

      },
      formDate: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: 1, // 题型
        difficulty: 1, // 难度
        question: '', // 题干
        // 选项
        options: [
          {
            code: 'A', // 选项
            img: '', // 图片
            title: '', // 文本
            isRight: false // 状态 0未选中 1选中
          },
          {
            code: 'B', // 选项
            img: '', // 图片
            title: '', // 文本
            isRight: false // 状态 0未选中 1选中
          },
          {
            code: 'C', // 选项
            img: '', // 图片
            title: '', // 文本
            isRight: false // 状态 0未选中 1选中
          },
          {
            code: 'D', // 选项
            img: '', // 图片
            title: '', // 文本
            isRight: false // 状态 0未选中 1选中
          }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      rules: {
        // 学科
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        // 目录
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        tags: [
          { required: true, message: '请选择标签', trigger: 'change' }
        ],
        // 企业
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        // 城市
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        // 地区
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        // 方向
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        // 题型
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        // 难度
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        // 题干
        question: [
          { required: true, validator: questionrules, trigger: 'change' }
        ],
        // 答案解析
        answer: [
          { required: true, validator: answerrules, trigger: 'change' }
        ]

      }
    }
  },
  mounted () {
    this.loadquestionFn() // 富文本
    this.loadDimpleFn() // 学科列表
    this.loadlistcompanysFn() // 企业列表
    this.loadProvincesFn() // 城市
    this.loaddirection() // 方向
    this.loadecho() // 回显
  },
  watch: {
    dx: {
      handler (newVal, oldVal) {
        this.formDate.options.forEach(item => {
          item.isRight = false
        })
        this.formDate.options[newVal].isRight = true
      },
      deep: true
    },
    checkList: {
      handler (newVal, oldVal) {
        this.formDate.options.forEach(item => {
          item.isRight = false
        })
        newVal.forEach(item => {
          this.formDate.options[item].isRight = true
        })
      },
      deep: true
    }
  },
  methods: {
    // 回显
    async loadecho () {
      if (this.$route.query.id) {
        const res = await detailecho({ id: this.$route.query.id })

        this.formDate = res.data
        // 回显难度
        this.formDate.difficulty = Number(res.data.difficulty)
        // 回显题型
        this.formDate.questionType = Number(res.data.questionType)
        // 回显选中
        var arr = this.formDate.options.filter(item => {
          return Number(item.isRight) === 1
        })

        if (arr.length === 1) {
          var b = this.formDate.options.findIndex(item => {
            return item.isRight === 1
          })
          this.dx = b
        } else {
          arr.forEach(v => {
            var b = this.formDate.options.findIndex(item => {
              return item.code === v.code
            })
            this.checkList.push(b)
          })
        }
        // 回显标签目录
        simpledirectorys({ subjectID: this.formDate.subjectID }).then(res => {
          this.formDateArr.catalogID = res.data
          if (this.formDateArr.catalogID.length === 0) {
            this.rules.catalogID[0].required = false
          } else {
            this.rules.catalogID[0].required = true
          }
        })
        listTags({ subjectID: this.formDate.subjectID }).then(res => {
          this.formDateArr.tags = res.data
          if (this.formDateArr.tags.length === 0) {
            this.rules.tags[0].required = false
          } else {
            this.rules.tags[0].required = true
          }
        })
        this.formDateArr.tag = this.formDate.tags.split(',')

        if (this.$route.query.id) {
          this.editor.txt.append(this.formDate.question)
          this.editor2.txt.append(this.formDate.answer)
        }
      }
    },
    // 富文本
    loadquestionFn () {
      function fn (v) {
        if (`${v}`) {
          document.querySelector('#question1').classList.add('question1')
        } else {
          document.querySelector('#question1').classList.remove('question1')
        }
      }
      function fn2 (v) {
        if (`${v}`) {
          document.querySelector('#question2').classList.add('question1')
        } else {
          document.querySelector('#question2').classList.remove('question1')
        }
      }
      const editor = new WangEditor('#question1')
      editor.config.menus = [
        'bold',
        'head',
        'italic',
        'underline',
        'image',
        'video',
        'table'
      ]

      // 配置 onchange 回调函数，将数据同步到 vue 中
      editor.config.onchange = (newHtml) => {
        this.formDate.question = newHtml
      }

      editor.config.onblur = (newHtml) => {
        this.$refs.formDate.validateField('question', (v) => {
          fn(v)
        })
      }

      // 创建编辑器

      editor.config.height = 200
      editor.config.zIndex = 0
      editor.config.focus = false
      editor.create()
      this.editor = editor

      const editor2 = new WangEditor('#question2')
      editor2.config.menus = [
        'bold',
        'head',
        'italic',
        'underline',
        'image',
        'video',
        'table'
      ]
      // 配置 onchange 回调函数，将数据同步到 vue 中
      editor2.config.onchange = (newHtml) => {
        this.formDate.answer = newHtml
      }
      editor2.config.onblur = (newHtml) => {
        this.$refs.formDate.validateField('answer', (v) => {
          fn2(v)
        })
      }
      // 创建编辑器
      editor2.config.height = 200
      editor2.config.zIndex = 0
      editor2.config.focus = false
      editor2.create()
      this.editor2 = editor2
    },
    // 加载学科列表
    loadDimpleFn () {
      simplesubjects().then(res => {
        this.formDateArr.subjectID = res.data
      })
    },
    // 获取目录 标签
    getDirectoryAndTag () {
      this.formDate.catalogID = ''
      this.formDate.tags = ''
      this.formDateArr.catalogID = []
      this.formDateArr.tags = []
      this.formDateArr.tag = []
      // 目录

      simpledirectorys({ subjectID: this.formDate.subjectID }).then(res => {
        this.formDateArr.catalogID = res.data
      })
      // 标签
      listTags({ subjectID: this.formDate.subjectID }).then(res => {
        this.formDateArr.tags = res.data
      })
    },
    // 加载企业列表
    loadlistcompanysFn () {
      listcompanys().then(res => {
        const arr = []
        res.data.items.forEach(item => {
          const obj = {
            value: '',
            label: ''
          }
          obj.value = item.id
          obj.label = item.shortName
          arr.push(obj)
        })
        this.formDateArr.enterpriseID = arr
      })
    },
    // 城市
    loadProvincesFn () {
      var arr = []
      provinces().forEach(item => {
        var obj = {
          value: '',
          label: ''
        }
        obj.value = item
        obj.label = item
        arr.push(obj)
      })
      this.formDateArr.province = arr
    },
    // 获取地区
    getcitys () {
      var arr = []
      if (!this.formDate.province) {
        this.formDateArr.city = []
        this.formDate.city = ''
        return
      }
      citys(this.formDate.province).forEach(item => {
        var obj = {
          value: '',
          label: ''
        }
        obj.value = item
        obj.label = item
        arr.push(obj)
      })
      this.formDate.city = arr[0].value
      this.formDateArr.city = arr
    },
    // 方向 题型 难度
    loaddirection () {
      var arr = []
      direction.forEach(item => {
        var obj = {
          value: '',
          label: ''
        }
        obj.value = item
        obj.label = item
        arr.push(obj)
      })
      this.formDateArr.difficulty = difficulty
      this.formDateArr.questionType = questionType
      this.formDateArr.direction = arr
    },
    // 题型变化
    changedx () {
      this.dx = ''
      this.checkList = []
      this.formDate.options = [
        {
          code: 'A', // 选项
          img: '', // 图片
          title: '', // 文本
          isRight: 0 // 状态 0未选中 1选中
        },
        {
          code: 'B', // 选项
          img: '', // 图片
          title: '', // 文本
          isRight: 0 // 状态 0未选中 1选中
        },
        {
          code: 'C', // 选项
          img: '', // 图片
          title: '', // 文本
          isRight: 0 // 状态 0未选中 1选中
        },
        {
          code: 'D', // 选项
          img: '', // 图片
          title: '', // 文本
          isRight: 0 // 状态 0未选中 1选中
        }
      ]
    },
    // 添加选项
    addcheck () {
      const i = this.formDateArr.mysort += 1

      this.formDate.options.push({
        code: String.fromCharCode(i), // 选项
        img: '', // 图片
        title: '', // 文本
        isRight: 0 // 状态 0未选中 1选中
      })
    },
    // 标签格式
    changeTags () {
      this.formDate.tags = this.formDateArr.tag.join(',')
    },
    // 提交
    submmit () {
      this.$refs.formDate.validate(async (valid) => {
        if (valid) {
          this.disabled = true
          this.formDate.questionType = String(this.formDate.questionType)
          this.formDate.difficulty = String(this.formDate.difficulty)

          if (this.$route.query.id) {
            await updateQuestions({ ...this.formDate, id: Number(this.$route.query.id) })
            this.$route.meta.title = '试题录入'
          } else {
            await addQuestions(this.formDate)
          }

          this.$message({
            message: this.$route.query.id ? '试题编辑成功' : '试题录入成功',
            type: 'success'
          })
          this.$router.push({
            path: '/questions/list'
          })
          this.editor.destroy()
          this.editor2.destroy()
          this.$refs.formDate.resetFields()
          this.disabled = false
        } else {
          return false
        }
      })
    }

  }
}
</script>

<style scoped lang='less'>

/deep/ .el-form-item__error {
  margin-left:  55px;
}
.mycity /deep/ .el-form-item__error {
  margin-left: 0;
}
.myquestion2 /deep/ .el-form-item__error {
  margin-left: 80px;
}
.container {
  margin: 20px 20px 0 20px;
}
/deep/ .el-card__body {
  padding-left: 80px;
}
/deep/ .cselect {
  margin-right: 10px;
}
/deep/.w-e-text-container, /deep/.w-e-toolbar{
  width: 740px;
}
#question1 {
margin-left: 60px;
}
#question2 {
margin-left: 82px;
}
.submmit {
  margin-left: 70px;
}
/deep/.el-checkbox-group {
  margin-left: 50px;
  margin-top: -30px;
}
.myradio {
  margin-bottom: 30px;
}
.ml {
  margin-left: 50px;
}
/deep/.city {

  position: relative;

}
/deep/.cityfd {
  position: absolute;
  bottom: 0px;

}
/deep/.mycity {
  height: 0;
  bottom: 22.5px;
  left: 280px;
  margin-bottom: 0;
}
.question1 {
  width: 742px;
  border: 1px solid #f56c6c;
}
.submmit {
  text-align: center;
}
</style>
